/*
 * Runner.cpp
 *
 *  Created on: 1.4.2011
 *      Author: Tomas Srna
 */

#include "Runner.h"

int Runner::run(int argc, char ** argv) {
	if(argc < 2)
	{
		std::cout << "Usage: " << argv[0]
		          << " tftproot [port=69]" << std::endl;
		return 1;
	}

	string tftproot = argv[1];
	int port = 69;

	if(argc > 2)
	{
		port = atoi(argv[2]);
		if(port < 1)
			cout << "Invalid port." << endl;
	}

	cout << "Inititalizing file source backend: ";
	IFile *fs = NULL;
	try
	{
		fs = Runner::fileFactory(tftproot);
		cout << "[ok]" << endl;
		cout << " - info: Backend type is " << fs->type() << endl;
	}
	catch(const char * e)
	{
		cout << "[fail]" << endl;
		cout << " - error: " << e << endl;

		return 1;
	}

	cout << "Running Listener." << endl;
	try
	{
		Listener l(fs, port, cout);
		l.run();
	}
	catch (const char * e)
	{
		cout << "Listener fail:" << endl;
		cout << " - error: " << e << endl;
	}

	delete fs;
	return 0;
}

IFile * Runner::fileFactory(const std::string& source)
{
	int l;
	if(3 < (l = source.size()) && source.substr(l-4) == ".tar")
		return new FileTAR(source);
	else
		return new FileFS(source);
}
